//
//  HomeViewController.swift
//  BA_MARRY_SWIFT
//
//  Created by 王洋 on 2021/5/13.
//

import UIKit
import HandyJSON



class HomeViewController: TT_BaseViewController {


    
    var homeModel:HomeModel?
    var homeHeadView:HomeHeadView?
    
//    var cell:UITableViewCell
    
    
    lazy var tableview : UITableView = {
        
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.white
        tableView.tableFooterView = UIView(frame: .zero)
        tableView.register(HomeBannerCell.self, forCellReuseIdentifier: "HomeBannerCellID")
        tableView.register(HomeSimpleImageCell.self, forCellReuseIdentifier: "HomeSimpleImageCellID")
        tableView.register(HomeMainIconCell.self, forCellReuseIdentifier: "HomeMainIconCellID")
        tableView.register(HomeMainIconCell.self, forCellReuseIdentifier: "HomeStrictlyStoreCellID")
        
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cid")

        
        tableView.separatorStyle = .none
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.scrollIndicatorInsets = tableView.contentInset
        }
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        initView()
        requestHomeAD()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: animated)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }

    func initView() -> Void {
        
        homeHeadView = UINib(nibName: "HomeHeadView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as? HomeHeadView
        
        self.view.addSubview(homeHeadView!)
        homeHeadView?.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.top.equalTo(0)
            make.height.equalTo(UIApplication.shared.statusBarFrame.height + 44)
        }
        
        self.view.addSubview(tableview)
        tableview.snp.makeConstraints { make in
            make.left.right.equalTo(0)
            make.bottom.equalTo(0)
            make.top.equalTo(homeHeadView!.snp.bottom).offset(0)
        }
    }

    func requestHomeAD() {

        let dic = NSMutableDictionary.init()
        dic .setValue("1", forKey: "pageNum")
        dic.setValue("10", forKey: "pageSize")
        dic.setValue("合肥", forKey: "cityName")
        
        TTHttpManager.postRequest(withUrl: ServerApiDefine.init().HomeADUrl, timeOut: 10, postData: dic as! [AnyHashable : Any]) { response in
            if response.success {
                let JSONString = dicValueString(response.data as! [String : Any])
                if let home = JSONDeserializer<HomeModel>.deserializeFrom(json: JSONString as String?) {
                    
                    let items:[HomeADItemModel] = (home.sysAdvTemplate?.sysAdvMoudleList)!
                    for item in items {
                        switch item.tadmId {
                        case 4:
                            item.itemHeight = 200
                            break
                        case 9:
                            item.itemHeight = HomeMainIconCell.calculateHeight()
                            break
                        case 50:
                            item.itemHeight = HomeMainIconCell.calculateHeight()
                            break
                        case 6:
                            item.itemHeight = HomeMainIconCell.calculateHeight()
                            break
                        case 51:
                            item.itemHeight = HomeMainIconCell.calculateHeight()
                            break
                        case 7:
                            item.itemHeight = HomeSimpleImageCell.calculateHeight()
                            break
                        case 13:
                            item.itemHeight = HomeStrictlyStoreCell.calculateHeight()
                            break
                        case 8:
                            item.itemHeight = HomeMainIconCell.calculateHeight()
                            break
                        case 45:
                            item.itemHeight = HomeMainIconCell.calculateHeight()
                            break
                        case 48:
                            item.itemHeight = HomeMainIconCell.calculateHeight()
                            break
                        default:
                            item.itemHeight = CGFloat.leastNormalMagnitude
                            break
                        }
                    }
                    
                    self.homeModel = home
                    self.tableview.reloadData();
                }
            }
        } failedBlock: { error in
        }
    }

}

// MARK: 字典转字符串
   func dicValueString(_ dic:[String : Any]) -> String?{
        let data = try? JSONSerialization.data(withJSONObject: dic, options: [])
        let str = String(data: data!, encoding: String.Encoding.utf8)
        return str
    }

extension HomeViewController:UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case Home_sectionType.Home_section_normal.rawValue:
            return self.homeModel?.sysAdvTemplate?.sysAdvMoudleList.count ?? 0
        case Home_sectionType.Home_section_recommand.rawValue:
            return 1
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case Home_sectionType.Home_section_normal.rawValue:
            let model:HomeADItemModel = (self.homeModel?.sysAdvTemplate?.sysAdvMoudleList[indexPath.row])!
            return model.itemHeight ?? CGFloat.leastNormalMagnitude;
        case Home_sectionType.Home_section_recommand.rawValue:
            return UIScreen.main.bounds.size.height
        default:
            return CGFloat.leastNormalMagnitude
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section ==  Home_sectionType.Home_section_recommand.rawValue{
            
            var cell:UITableViewCell! = tableview.dequeueReusableCell(withIdentifier: "cid")
            if cell == nil {
                cell = UITableViewCell.init(style: .default, reuseIdentifier: "cid")
            }
            
            let bg:UIView = UIView.init()
            cell .addSubview(bg)
            bg.backgroundColor = UIColor.lightGray
            bg.snp.makeConstraints { make in
                make.left.right.top.bottom.equalTo(0)
            }
            
            cell.selectionStyle = UITableViewCell.SelectionStyle.none
            return cell
            
        } else {
            
            let model:HomeADItemModel = (self.homeModel?.sysAdvTemplate?.sysAdvMoudleList[indexPath.row])!
            switch model.tadmId {
            case Home_itemType.Home_itemType_bigBanner.rawValue:
                
                var cell:HomeBannerCell! = tableView.dequeueReusableCell(withIdentifier: "HomeBannerCellID") as? HomeBannerCell
                if cell == nil {
                    cell = HomeBannerCell.init(style: .default, reuseIdentifier: "HomeBannerCellID")
                }
                cell.selectionStyle = UITableViewCell.SelectionStyle.none
                
                cell.fillCellWithModel(model: model)
                return cell

            case Home_itemType.Home_itemType_gird.rawValue:
                
                var cell:HomeMainIconCell! = tableView.dequeueReusableCell(withIdentifier: "HomeMainIconCellID") as? HomeMainIconCell
                if cell == nil {
                    cell = HomeMainIconCell.init(style: .default, reuseIdentifier: "HomeMainIconCellID")
                }
                cell.selectionStyle = UITableViewCell.SelectionStyle.none
                cell.fillCellWithModel(model: model)
                return cell

            case Home_itemType.Home_itemType_mixGird.rawValue:
                var cell:HomeMainIconCell! = tableView.dequeueReusableCell(withIdentifier: "HomeMainIconCellID") as? HomeMainIconCell
                if cell == nil {
                    cell = HomeMainIconCell.init(style: .default, reuseIdentifier: "HomeMainIconCellID")
                }
                cell.selectionStyle = UITableViewCell.SelectionStyle.none
                return cell

            case Home_itemType.Home_itemType_icon.rawValue:
                var cell:HomeMainIconCell! = tableView.dequeueReusableCell(withIdentifier: "HomeMainIconCellID") as? HomeMainIconCell
                if cell == nil {
                    cell = HomeMainIconCell.init(style: .default, reuseIdentifier: "HomeMainIconCellID")
                }
                cell.selectionStyle = UITableViewCell.SelectionStyle.none
                cell.fillCellWithModel(model: model)
                return cell

            case Home_itemType.Home_itemType_mixIcon.rawValue:
                var cell:HomeMainIconCell! = tableView.dequeueReusableCell(withIdentifier: "HomeMainIconCellID") as? HomeMainIconCell
                if cell == nil {
                    cell = HomeMainIconCell.init(style: .default, reuseIdentifier: "HomeMainIconCellID")
                }
                cell.selectionStyle = UITableViewCell.SelectionStyle.none
                cell.fillCellWithModel(model: model)
                return cell

            case Home_itemType.Home_itemType_title.rawValue:
                var cell:HomeSimpleImageCell! = tableView.dequeueReusableCell(withIdentifier: "HomeSimpleImageCellID") as? HomeSimpleImageCell
                if cell == nil {
                    cell = HomeSimpleImageCell.init(style: .default, reuseIdentifier: "HomeSimpleImageCellID")
                }
                cell.selectionStyle = UITableViewCell.SelectionStyle.none
                cell.fillCellWithModel(model: model)
                return cell

            case Home_itemType.Home_itemType_YXStore.rawValue:
                var cell:HomeStrictlyStoreCell! = tableView.dequeueReusableCell(withIdentifier: "HomeStrictlyStoreCellID") as? HomeStrictlyStoreCell
                if cell == nil {
                    cell = HomeStrictlyStoreCell.init(style: .default, reuseIdentifier: "HomeStrictlyStoreCellID")
                }
                cell.selectionStyle = UITableViewCell.SelectionStyle.none
                cell.fillCellWithModel(model: model)
                return cell

            case Home_itemType.Home_itemType_xBanner.rawValue:
                var cell:HomeBannerCell! = tableView.dequeueReusableCell(withIdentifier: "HomeBannerCellID") as? HomeBannerCell
                if cell == nil {
                    cell = HomeBannerCell.init(style: .default, reuseIdentifier: "HomeBannerCellID")
                }
                cell.selectionStyle = UITableViewCell.SelectionStyle.none
                cell.fillCellWithModel(model: model)
                return cell

            case Home_itemType.Home_itemType_newFree.rawValue:
                var cell:HomeBannerCell! = tableView.dequeueReusableCell(withIdentifier: "HomeBannerCellID") as? HomeBannerCell
                if cell == nil {
                    cell = HomeBannerCell.init(style: .default, reuseIdentifier: "HomeBannerCellID")
                }
                cell.selectionStyle = UITableViewCell.SelectionStyle.none
                cell.fillCellWithModel(model: model)
                return cell

            case Home_itemType.Home_itemType_newGird.rawValue:
                var cell:HomeBannerCell! = tableView.dequeueReusableCell(withIdentifier: "HomeBannerCellID") as? HomeBannerCell
                if cell == nil {
                    cell = HomeBannerCell.init(style: .default, reuseIdentifier: "HomeBannerCellID")
                }
                cell.selectionStyle = UITableViewCell.SelectionStyle.none
                cell.fillCellWithModel(model: model)
                return cell

            default:
                var cell:HomeBannerCell! = tableView.dequeueReusableCell(withIdentifier: "HomeBannerCellID") as? HomeBannerCell
                if cell == nil {
                    cell = HomeBannerCell.init(style: .default, reuseIdentifier: "HomeBannerCellID")
                }
                cell.selectionStyle = UITableViewCell.SelectionStyle.none
                return cell
                
            }
        }
    }
}
